package com.csh.szhm.activity;

import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.csh.szhm.R;
import com.csh.szhm.adapter.SzhmSelectAreaLeftAdapter;
import com.csh.szhm.adapter.SzhmSelectAreaRightAdapter;
import com.csh.szhm.adapter.SzhmSelectTypeLeftAdapter;
import com.csh.szhm.adapter.SzhmSelectTypeRightAdapter;
import com.csh.szhm.adapter.SzhmSortThreeAdapter;
import com.csh.szhm.http.HttpCallBackUi;
import com.csh.szhm.http.HttpRequestTool;
import com.csh.szhm.http.HttpUrls;
import com.csh.szhm.module.search.SzhmSearchBean;
import com.csh.szhm.module.search.SzhmSearchItemBean;
import com.csh.szhm.module.search.SzhmSearchListBean;
import com.csh.szhm.module.search.SzhmSearchTypeBean;
import com.csh.szhm.module.search.SzhmSearchTypeListBean;
import com.csh.szhm.module.shop.ShopListItem;
import com.csh.szhm.module.shop.ShopListItemBean;
import com.csh.szhm.utils.AppConfig;
import com.csh.szhm.utils.DebugUntil;
import com.csh.szhm.utils.StringUtil;
import com.csh.szhm.utils.sharepreferences.SharedPreferencesUtil;
import com.google.gson.reflect.TypeToken;

public class SzhmSortThreeMainActiviy extends
		MyRefreshBaseActivity<ShopListItem> {

	private int[] titleText = new int[] { R.string.title_txt_1,
			R.string.title_txt_2, R.string.title_txt_3, R.string.title_txt_4,
			R.string.title_txt_5, R.string.title_txt_6 };
	private int[] imgArr = new int[] { R.id.sort_1_img, R.id.sort_2_img,
			R.id.sort_3_img };
	private int mActivityType;
	private TextView txt1;
	private TextView txt2;
	private TextView txt3;
	private TextView[] text = new TextView[3];
	private int mType_S;
	private String keyword;
	private int mCurrentPos;

	@Override
	protected void init() {
		mActivityType = getIntent().getIntExtra("type", 0);
		keyword = getIntent().getStringExtra("search");
		mType_S = getIntent().getIntExtra("type_s", 0);
		initContentView(R.layout.szhm_cyms_main_layout);
		txt1 = (TextView) findViewById(R.id.sort_1_txt);
		txt2 = (TextView) findViewById(R.id.sort_2_txt);
		txt3 = (TextView) findViewById(R.id.sort_3_txt);
		text[0] = txt1;
		text[1] = txt2;
		text[2] = txt3;
		if (mType_S == -1) {
			// 找商户
			findViewById(R.id.szhm_cyms_search_root_id)
					.setVisibility(View.GONE);
			// setMyTitle("找商户");
			setMyTitle(new Integer[] { selectActivityTitleType() });
		} else {
			setMyTitle(new Integer[] { selectActivityTitleType() });
			// setMyTitle(new Integer[] { selectActivityTitleType(),
			// R.drawable.select_map });
		}
		super.init();
		mAdapter = new SzhmSortThreeAdapter(this);
		mLikeListView.setAdapter(mAdapter);
		mLikeListView.setSelector(getResources().getDrawable(
				R.drawable.all_select));
		mLikeListView.setBackgroundColor(getResources().getColor(
				R.color.main_bg));
		shouCustomProgressDialog();
		if (mType_S == -1) {
			if (!StringUtil.isEmptyString(keyword)) {
				setMyTitle(keyword);
			}
			requestNet();
		} else {
			getSerachData();
			getShopType();
		}
		text[1].setText(selectActivityTitleType());
	}

	private List<SzhmSearchBean> mAllArea;
	// private List<SzhmSearchBean> mAllType;
	private List<SzhmSearchTypeBean> mTypeData;

	private void getSerachData() {
		HttpRequestTool<SzhmSearchListBean> http = new HttpRequestTool<SzhmSearchListBean>();
		TypeToken<SzhmSearchListBean> ty = new TypeToken<SzhmSearchListBean>() {
		};
		http.setHttpCallBackUi(new HttpCallBackUi<SzhmSearchListBean>() {

			@Override
			public void success(SzhmSearchListBean data) {
				if (data != null) {
					String cityName = SharedPreferencesUtil.getInstance()
							.getCityName();

					mAllArea = data.getList();
					for (int i = 0; i < mAllArea.size(); i++) {
						if (cityName.equals(mAllArea.get(i).getName())) {
							// 当前城市名
							leftSelectPostion = i + 1;
							cityId = mAllArea.get(i).getId();
						}
						SzhmSearchItemBean temp12 = new SzhmSearchItemBean();
						temp12.setId("-1");
						temp12.setName("全部");
						mAllArea.get(i).getCountyList().add(0, temp12);
					}
					if (!StringUtil.isEmptyString(cityName)) {
						text[0].setText(cityName);
					}
					List<SzhmSearchItemBean> temp1 = new ArrayList<SzhmSearchItemBean>();
					SzhmSearchItemBean temp2 = new SzhmSearchItemBean();
					temp2.setId("-1");
					temp2.setName("全部");
					temp1.add(temp2);
					SzhmSearchBean bean = new SzhmSearchBean();
					bean.setCountyList(temp1);
					bean.setId("-1");
					bean.setName("全部地区");
					mAllArea.add(0, bean);
					requestNet();
				}
			}

			@Override
			public void requestType(String Type) {
			}

			@Override
			public void failed(VolleyError error) {
				dissmisCustomProgressDialog();
			}
		});
		http.cloneRequest(Method.GET, HttpUrls.mSearchType, ty, getClass()
				.getSimpleName(), "SEARCH");
	}

	private void getShopType() {
		HttpRequestTool<SzhmSearchTypeListBean> http = new HttpRequestTool<SzhmSearchTypeListBean>();
		TypeToken<SzhmSearchTypeListBean> ty = new TypeToken<SzhmSearchTypeListBean>() {
		};
		http.setHttpCallBackUi(new HttpCallBackUi<SzhmSearchTypeListBean>() {

			@Override
			public void success(SzhmSearchTypeListBean data) {
				if (data != null) {
					if (data.getFirmTpList() != null
							&& data.getFirmTpList().size() > 0) {
						mTypeData = getTypeData(data.getFirmTpList(), "");
						// if (mActivityType == 4) {
						// mCurrentPos = 5 - 1;
						// } else if (mActivityType == 5) {
						// mCurrentPos = (4 - 1);
						// } else {
						// mCurrentPos = (mActivityType - 1);
						// }
						if (mActivityType == 152) {
							mCurrentPos = 5;
						} else
							mCurrentPos = (mActivityType - 1);
						// findViewById(R.id.sort_2).setTag((mCurrentPos-1 ) +
						// "-" + 0);
					}
				}
			}

			@Override
			public void requestType(String Type) {
			}

			@Override
			public void failed(VolleyError error) {
				dissmisCustomProgressDialog();
			}
		});
		http.cloneRequest(Method.GET, HttpUrls.mShopSearchType, ty, getClass()
				.getSimpleName(), "SearchType");
	}

	private List<SzhmSearchTypeBean> getTypeData(List<SzhmSearchTypeBean> d,
			String pid) {
		List<SzhmSearchTypeBean> r = new ArrayList<SzhmSearchTypeBean>();
		for (SzhmSearchTypeBean item : d) {
			if (item.getParentId().equals(pid)) {
				SzhmSearchTypeBean data = new SzhmSearchTypeBean();
				data.setId(item.getId());
				data.setName(item.getName());
				data.setParentId(item.getParentId());
				data.setItems(getTypeData(d, item.getId()));
				r.add(data);
			}
		}
		return r;
	}

	private HttpRequestTool<ShopListItemBean> mHttpRequestTool;
	private TypeToken<ShopListItemBean> token;

	@Override
	protected void requestNet() {
		if (mHttpRequestTool == null) {
			mHttpRequestTool = new HttpRequestTool<ShopListItemBean>();
			token = new TypeToken<ShopListItemBean>() {
			};
			mHttpRequestTool
					.setHttpCallBackUi(new HttpCallBackUi<ShopListItemBean>() {
						@Override
						public void success(ShopListItemBean data) {
							mLikeListView.stopCommplete();
							dissmisCustomProgressDialog();
							if (isRefresh) {
								mAdapter.clearAll();
								isRefresh = false;
							}
							if (data != null) {
								List<ShopListItem> list = data.getFirmList();
								if (list != null && list.size() > 0) {
									stopOnLoad(list.size());
									mAdapter.addData(list);
								} else {
									stopOnLoad(list.size());
									DebugUntil.createInstance().toastStr(
											"无更多数据");
								}
							} else {
								stopOnLoad(0);
							}
						}

						@Override
						public void requestType(String Type) {
							// TODO Auto-generated method stub
						}

						@Override
						public void failed(VolleyError error) {
							dissmisCustomProgressDialog();
							mLikeListView.stopCommplete();
						}
					});
		}
		if (mType_S == -1) {
			if (StringUtil.isEmptyString(keyword)) {
				mHttpRequestTool.cloneRequest(Method.GET, HttpUrls.mShopSearch
						+ "?firmQueryVo.firmType=" + mActivityType
						+ getCurrentPage(), token, getClass().getSimpleName(),
						"SEARCH_LIST");
			} else {
				mHttpRequestTool.cloneRequest(Method.GET, HttpUrls.mShopSearch
						+ "?keyword=" + AppConfig.urlEncode(keyword)
						+ getCurrentPage(), token, getClass().getSimpleName(),
						"SEARCH_LIST");
			}
		} else {
			mHttpRequestTool.cloneRequest(Method.GET, HttpUrls.mShopSearch
					+ "?firmQueryVo.firmType=" + mActivityType
					+ "&firmQueryVo.firmType2=" + oneId
					+ "&firmQueryVo.firmType3=" + twoId
					+ "&firmQueryVo.areaCity=" + cityId
					+ "&firmQueryVo.county=" + areaId + getCurrentPage(),
					token, getClass().getSimpleName(), "SEARCH_LIST");
		}
	}

	private int selectActivityTitleType() {
		if (mActivityType == 152) {
			return titleText[titleText.length - 1];
		}
		for (int i = 0; i < titleText.length; i++) {
			if (i == (mActivityType - 1)) {
				// if (i == 3) {
				// return titleText[4];
				// }
				// if (i == 4) {
				// return titleText[3];
				// }
				return titleText[i];
			}
		}
		return titleText[0];
	}

	private ListView mLeftListView;
	private ListView mRightListView;
	private PopupWindow mPopupWindow;
	private SzhmSelectAreaLeftAdapter mSzhmSelectAreaLeftAdapter;
	private SzhmSelectAreaRightAdapter mSzhmSelectAreaRightAdapter;
	private SzhmSelectTypeLeftAdapter mSzhmSelectTypeLeftAdapter;
	private SzhmSelectTypeRightAdapter mSzhmSelectTypeRightAdapter;

	/**
	 * 初始化搜索条件弹出框
	 * 
	 * @param id
	 */
	public void initpopupwindow(int id) {
		if (mLeftListView == null) {
			LayoutInflater layoutInflater = LayoutInflater.from(this);
			View popupwindow = layoutInflater.inflate(
					R.layout.szhm_sort_select_layout, null);
			popupwindow.findViewById(R.id.popu_buttom_root_id)
					.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							mPopupWindow.dismiss();
							setImgPisition(-1);
						}
					});
			mLeftListView = (ListView) popupwindow
					.findViewById(R.id.lv_cla_area);
			mRightListView = (ListView) popupwindow
					.findViewById(R.id.lv_cla_area_next);
			mLeftListView.setCacheColorHint(Color.TRANSPARENT);// 删滑动背景
			// lv_cla_area.setBackgroundResource(R.drawable.clas_pop_left_back_1);
			mRightListView.setCacheColorHint(Color.TRANSPARENT);
			mLeftListView.setDivider(null);
			mRightListView.setDivider(null);
			mLeftListView.setSelector(R.drawable.all_select);
			mRightListView.setSelector(R.drawable.all_select);
			mPopupWindow = new PopupWindow(popupwindow,
					AppConfig.getScreenWidth(), AppConfig.getScreenHeight());
			mPopupWindow.setAnimationStyle(R.style.popwin_anim_style);
			mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			mPopupWindow.setOutsideTouchable(true);
			mPopupWindow.setFocusable(true);
			mPopupWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					// TODO Auto-generated method stub
					setImgPisition(-1);
				}
			});
		}
		if (id == R.id.sort_3) {
			// 只有一种情况
			mLeftListView.setVisibility(View.GONE);
			if (mSzhmSelectAreaRightAdapter == null) {
				mSzhmSelectAreaRightAdapter = new SzhmSelectAreaRightAdapter(
						this);
				mRightListView.setAdapter(mSzhmSelectAreaRightAdapter);
			}
			mSzhmSelectAreaRightAdapter.clearAll();
			mSzhmSelectAreaRightAdapter
					.addData(mAllArea.get(2).getCountyList());
		} else {
			mLeftListView.setVisibility(View.VISIBLE);
		}
		if (id == R.id.sort_1) {
			if (mSzhmSelectAreaLeftAdapter == null) {
				mSzhmSelectAreaLeftAdapter = new SzhmSelectAreaLeftAdapter(this);
				mSzhmSelectAreaRightAdapter = new SzhmSelectAreaRightAdapter(
						this);
			}
			mLeftListView.setAdapter(mSzhmSelectAreaLeftAdapter);
			mRightListView.setAdapter(mSzhmSelectAreaRightAdapter);
			if (mAllArea != null && mAllArea.size() > 0) {
				mSzhmSelectAreaLeftAdapter.clearAll();
				mSzhmSelectAreaLeftAdapter.addData(mAllArea);
				mSzhmSelectAreaRightAdapter.clearAll();
				mSzhmSelectAreaRightAdapter.addData(mAllArea.get(
						getLeftPosition(id)[0]).getCountyList());
			}
			mSzhmSelectAreaLeftAdapter
					.setSelectPosition(getLeftPosition(id)[0]);
			mSzhmSelectAreaRightAdapter
					.setSelectPosition(getLeftPosition(id)[1]);
			findViewById(id).setTag(
					getLeftPosition(id)[0] + "-" + getLeftPosition(id)[1]);
		} else if (id == R.id.sort_2) {
			if (mSzhmSelectTypeLeftAdapter == null) {
				mSzhmSelectTypeLeftAdapter = new SzhmSelectTypeLeftAdapter(this);
				mSzhmSelectTypeRightAdapter = new SzhmSelectTypeRightAdapter(
						this);
			}
			mLeftListView.setAdapter(mSzhmSelectTypeLeftAdapter);
			mRightListView.setAdapter(mSzhmSelectTypeRightAdapter);
			if (mTypeData != null && mTypeData.size() > 0) {
				mSzhmSelectTypeLeftAdapter.clearAll();
				mSzhmSelectTypeRightAdapter.clearAll();
				mSzhmSelectTypeLeftAdapter.addData(addAll(mTypeData.get(
						mCurrentPos).getItems()));
				mSzhmSelectTypeRightAdapter.addData(addTypeAll(mTypeData
						.get(mCurrentPos).getItems()
						.get(getLeftPosition(id)[0]).getItems()));
			}
			mSzhmSelectTypeLeftAdapter
					.setSelectPosition(getLeftPosition(id)[0]);
			mSzhmSelectTypeRightAdapter
					.setSelectPosition(getLeftPosition(id)[1]);
			findViewById(id).setTag(
					getLeftPosition(id)[0] + "-" + getLeftPosition(id)[1]);
		} else {

		}
		mLeftListView.setOnItemClickListener(new MyItemClickListener(id));
		mRightListView.setOnItemClickListener(new MySubItemClickListener(id));

		mLeftListView.setSelection(getLeftPosition(id)[0]);
		mRightListView.setSelection(getLeftPosition(id)[1]);
	}

	private List<SzhmSearchTypeBean> addAll(List<SzhmSearchTypeBean> ls) {
		if (ls != null && ls.size() > 0) {
			if (ls.get(0).getId().equals("-1")) {
				return ls;
			}
			SzhmSearchTypeBean bean = new SzhmSearchTypeBean();
			bean.setId("-1");
			bean.setName(getResources().getString(selectActivityTitleType()));
			ls.add(0, bean);
		}
		return ls;

	}

	private List<SzhmSearchTypeBean> addTypeAll(List<SzhmSearchTypeBean> ls) {
		if (ls != null && ls.size() > 0) {
			if (ls.get(0).getId().equals("-1")) {
				return ls;
			}
			SzhmSearchTypeBean bean = new SzhmSearchTypeBean();
			bean.setId("-1");
			bean.setName("全部");
			ls.add(0, bean);
		}
		return ls;

	}

	private int[] getLeftPosition(int id) {
		int[] num = new int[] { 0, 0 };
		String str = (String) findViewById(id).getTag();
		if (StringUtil.isEmptyString(str)) {
			return num;
		}
		String[] st = str.split("-");
		if (StringUtil.isEmptyString(st[0]) || StringUtil.isEmptyString(st[1])) {
			return num;
		}
		num[0] = Integer.valueOf(st[0]);
		num[1] = Integer.valueOf(st[1]);
		return num;
	}

	private void setImgPisition(int id) {
		for (int i = 0; i < imgArr.length; i++) {
			if (id == imgArr[i]) {
				findViewById(imgArr[i]).setVisibility(View.VISIBLE);
			} else {
				findViewById(imgArr[i]).setVisibility(View.GONE);
			}
		}
	}

	private int leftSelectPostion = 0;
	private int rightSelectPostion = 0;
	private int tempLeft;
	private String cityId = "\"\"";
	private String areaId = "\"\"";
	private String oneId = "\"\"";
	private String twoId = "\"\"";

	private class MyItemClickListener implements OnItemClickListener {
		private int viewId;

		public MyItemClickListener(int id) {
			viewId = id;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

			if (viewId == R.id.sort_1) {
				findViewById(viewId).setTag(arg2 + "-" + rightSelectPostion);
				leftSelectPostion = arg2;
				mSzhmSelectAreaLeftAdapter.setSelectPosition(arg2);
				mSzhmSelectAreaRightAdapter.clearAll();
				mSzhmSelectAreaRightAdapter.addData(mAllArea.get(arg2)
						.getCountyList());
				mSzhmSelectAreaRightAdapter.notifyDataSetChanged();
			} else if (viewId == R.id.sort_2) {
				mSzhmSelectTypeRightAdapter.clearAll();
				mSzhmSelectTypeLeftAdapter.setSelectPosition(arg2);
				mSzhmSelectTypeRightAdapter.setSelectPosition(-1);
				if (arg2 == 0) {
					// 全部
					text[1].setText(mSzhmSelectTypeLeftAdapter.getItem(0)
							.getName());
					findViewById(viewId).setTag(0 + "-" + 0);
					mPopupWindow.dismiss();
					oneId = "\"\"";
					twoId = "\"\"";
				} else {
					tempLeft = arg2;
					findViewById(viewId).setTag(arg2 + "-" + 0);
					int size = mTypeData.get(mCurrentPos).getItems().size();
					if (size == 0) {
						mSzhmSelectTypeRightAdapter.addData(null);
					} else {
						mSzhmSelectTypeRightAdapter
								.addData(addTypeAll(mTypeData.get(mCurrentPos)
										.getItems()
										.get(getLeftPosition(viewId)[0])
										.getItems()));
					}
				}
				mSzhmSelectTypeRightAdapter.notifyDataSetChanged();
			}

		}
	}

	private class MySubItemClickListener implements OnItemClickListener {
		private int viewId;

		public MySubItemClickListener(int id) {
			viewId = id;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

			mPopupWindow.dismiss();

			int currentPos;
			if (viewId == R.id.sort_1) {
				rightSelectPostion = arg2;
				findViewById(viewId).setTag(leftSelectPostion + "-" + arg2);
				currentPos = 0;
				areaId = mSzhmSelectAreaRightAdapter.getItem(arg2).getId();
				cityId = mSzhmSelectAreaLeftAdapter.getItem(leftSelectPostion)
						.getId();
				if (cityId.equals("-1")) {
					cityId = "\"\"";
				}
				if (areaId.equals("-1")) {
					areaId = "\"\"";
				}
				if (leftSelectPostion == 0) {
					// 选择的还是第一个
					text[currentPos].setText(mSzhmSelectAreaLeftAdapter
							.getItem(getLeftPosition(viewId)[0]).getName());
				} else {
					if (arg2 == 0) {
						// 表示全部
						text[currentPos].setText(mSzhmSelectAreaLeftAdapter
								.getItem(getLeftPosition(viewId)[0]).getName());
					} else {
						text[currentPos].setText(mSzhmSelectAreaRightAdapter
								.getItem(getLeftPosition(viewId)[1]).getName());
					}
				}
			} else if (viewId == R.id.sort_2) {

				findViewById(viewId).setTag(tempLeft + "-" + arg2);
				currentPos = 1;
				if (arg2 == 0) {
					// 第一个
					text[currentPos].setText(mSzhmSelectTypeLeftAdapter
							.getItem(getLeftPosition(viewId)[0]).getName());
					twoId = "\"\"";
				} else {
					text[currentPos].setText(mSzhmSelectTypeRightAdapter
							.getItem(getLeftPosition(viewId)[1]).getName());
					twoId = mSzhmSelectTypeRightAdapter.getItem(
							getLeftPosition(viewId)[1]).getId();
				}
				oneId = mSzhmSelectTypeLeftAdapter.getItem(
						getLeftPosition(viewId)[0]).getId();

			} else {
				currentPos = 2;
			}
			if (currentPos == 2) {
				text[currentPos].setText(mSzhmSelectAreaRightAdapter.getItem(
						arg2).getName());
			} else {

			}

			loadData();
		}
	}

	private void loadData() {
		setImgPisition(-1);
		stopOnLoad(0);
		onRefresh();
	}

	@Override
	public void click(View v) {
		switch (v.getId()) {
		case R.id.sort_1:
			initpopupwindow(v.getId());
			mPopupWindow.showAsDropDown(v);
			setImgPisition(imgArr[0]);
			break;
		case R.id.sort_2:
			initpopupwindow(v.getId());
			mPopupWindow.showAsDropDown(v);
			setImgPisition(imgArr[1]);
			break;
		case R.id.sort_3:
			initpopupwindow(v.getId());
			mPopupWindow.showAsDropDown(v);
			setImgPisition(imgArr[2]);
			break;
		case R.id.szhm_title_right_root:
			// Intent in = new Intent();
			// in.putExtra("type", mActivityType);
			// startMyActivity(in, SzhmOverlyMainActivity.class);
			break;
		}
		super.click(v);
	}

	@Override
	protected void onMyItemClick(ShopListItem item) {

		Intent in = new Intent();
		in.putExtra("id", item.getFirmId());
		startMyActivity(in, SzhmShopDetailActivity.class);
		super.onMyItemClick(item);
	}

}
